<template>
	<el-dialog v-model="dialog" title="分配菜单" width="50%" destroy-on-close>
		<div class="hx-menus">
			<el-tree ref="menuRef" :data="menuList" :props="defaultProps" node-key="id" show-checkbox @check="handleChange">
				<template #default="{ node, data }">
					<span class="custom-tree-node">
						<span>{{ $t(node.label) }}</span>
					</span>
				</template></el-tree>
		</div>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialog = false">取 消</el-button>
				<el-button type="primary" @click="onsubmit" :loading="loading">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, nextTick } from 'vue';
import { getUserMenu, getMenusByRole } from '/@/api/upms/menu';
import { saveRoleMenu } from '/@/api/upms/sysrole';
import { ElMessage, ElTree } from 'element-plus';

interface dataState {
	menuList: Array<any>;
	menuIds: Array<string>;
}
export default defineComponent({
	emits: ['initPage'],
	setup(props, { emit }) {
		const menuRef = ref();
		const dialog = ref(false);
		const data = reactive<dataState>({ menuList: [], menuIds: [] });
		const roleId = ref();
		const loading = ref(false);
		const defaultProps = {
			children: 'children',
			label: 'label',
			disabled: 'disabled',
		};
		/**
		 * 选择菜单权限事件
		 */
		const handleChange = () => {
			let checkedKeys = menuRef.value.getCheckedKeys(false);
			let halfCheckedKeys = menuRef.value.getHalfCheckedKeys(false);
			data.menuIds = [...checkedKeys, ...halfCheckedKeys];
		};
		/**
		 * 查询菜单树数据
		 */
		const getMenuList = () => {
			getUserMenu().then((response: any) => {
				data.menuList = response.data.data;
			});
		};
		/**
		 * 获取指定角色的菜单
		 */
		const getRoleMenus = (id: string) => {
			roleId.value = id;
			getMenusByRole({ roleId: id }).then((response: any) => {
				if (response.data.data) {
					data.menuIds = response.data.data;
					response.data.data.forEach((id: string) => {
						nextTick(() => {
							menuRef.value.setChecked(id, true, false);
						});
					});
				}
			});
		};
		const onsubmit = () => {
			loading.value = true;
			saveRoleMenu({ roleId: roleId.value, menuIds: data.menuIds }).then((response: any) => {
				loading.value = false;
				ElMessage.success('更新成功');
				dialog.value = false;
				emit('initPage');
			});
		};
		getMenuList();
		return {
			dialog,
			menuRef,
			defaultProps,
			roleId,
			loading,
			onsubmit,
			getMenuList,
			getRoleMenus,
			handleChange,
			...toRefs(data),
		};
	},
});
</script>
<style>
.hx-menus {
	height: 500px;
	overflow-y: auto;
	width: 100%;
	border: 1px solid #dcdee0;
	padding: 4px;
	border-radius: 4px;
}
</style>
